<template>
  <div>
    <el-dialog :visible.sync="dialogVisible" class="elTable" width="700px" @open="listFileMessage">
      <el-table :data="fileMessageList" height="550px">
        <el-table-column property="msgContent" label="文件名" class="el-first" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <p style="color:#53c7f0; font-weight:bold">{{scope.row.msgContent}}</p>
          </template>
        </el-table-column>
        <el-table-column property="sendTime" label="发送时间" width="150px" :show-overflow-tooltip="true"/>
        <el-table-column property="msgFrom" label="发送者" width="150px" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" width="100px">
          <template slot-scope="scope">
            <el-button size="mini" @click="download(scope.row.msgContent, scope.row.msgAttach)">
              <i class="el-icon-download"></i>下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'FileDialog',
  props: {
    visible: Boolean
  },
  data () {
    return {
      dialogVisible: false,
      fileMessageList: []
    }
  },
  watch: {
    visible () {
      this.dialogVisible = this.visible
    },
    dialogVisible () {
      this.$emit('update:visible', this.dialogVisible)
    }
  },
  methods: {
    listFileMessage () {
      this.$axios.get('/api/message/file')
        .then(response => {
          let result = response.data
          if (result.success) {
            this.fileMessageList = result.data
          } else {
            this.$message.error(result.msg)
          }
        })
    },
    download (msgContent, msgAttach) {
      this.$axios({
        url: msgAttach,
        method: 'get',
        responseType: 'blob'
      }).then(response => {
        // 创建隐藏的可下载链接
        var eleLink = document.createElement('a')
        eleLink.download = msgContent
        eleLink.style.display = 'none'
        // 字符内容转变成blob地址
        var blob = new Blob([response.data])
        eleLink.href = URL.createObjectURL(blob)
        // 触发点击
        document.body.appendChild(eleLink)
        eleLink.click()
        // 然后移除
        document.body.removeChild(eleLink)
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
.elTable >>> .cell {
  text-align: center;
}

.elTable >>> .el-dialog__body {
  padding-top: 10px;
}

.elTable {
  text-align: center;
}
</style>
